package com.shijiwei.lifthelper.utils;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.widget.RadioGroup;

import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;

import java.util.List;

/**
 * Created by sjw on 2015/12/9.
 */
public class FragmentUtils implements RadioGroup.OnCheckedChangeListener{

    private List<Fragment> list;
    private RadioGroup group;
    private int containerId;
    private FragmentManager manager;
    private FragmentTransaction transaction;
    private SlidingMenu menu;


    public FragmentUtils(List<Fragment> list, RadioGroup group, FragmentManager manager, int containerId,SlidingMenu menu) {
        this.list = list;
        this.group = group;
        this.manager = manager;
        this.containerId = containerId;
        this.menu = menu;
        //设置打来程序默认显示的Fragmet
        getFragmentTransaction().add(containerId,list.get(0)).show(list.get(0)).commit();
        //给RadioGroup设置点击事件
        group.setOnCheckedChangeListener(this);
    }


    /**
     * 选择相应的RadioButton 、切换对应的Fragement
     * @param group
     * @param checkedId
     */
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        for (int i = 0; i < group.getChildCount(); i++) {
            Fragment fragement = list.get(i);
            transaction = getFragmentTransaction();

            if (group.getChildAt(i).getId() == checkedId){ //选中项
                if (fragement.isAdded()){//已经加入到Activity
                    transaction.show(fragement).commit();
                }else { //没有加入到Activity
                    transaction.add(containerId,fragement).show(fragement).commit();
                }
                menu.toggle();
            }else { //没有被选中
                if (fragement.isAdded()){
                    transaction.hide(fragement).commit();
                }
            }
        }
    }

    /**
     * 获得事务
     * @return
     */
    public FragmentTransaction getFragmentTransaction(){
        transaction = manager.beginTransaction();
//        transaction.setCustomAnimations()
        // TO DO 添加动画
        return  transaction;
    }

}
